package first.program;

import java.util.ArrayList;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class GameScreen extends Activity implements OnClickListener {
	
	private static final int feedbackConstant = 3;
	final Verify checkrow = new Verify();
	public static final String PREFS_NAME = "MyPrefsFile";
	
	Button activebutton = null;
	Button [] [] button_guesses = new Button[10][5];
	ArrayList<Button> colors = new ArrayList<Button>();
	int active_row = 0;
	int active_position = 1;
	String activePosition [] =  {"1", "2", "3", "4"};
	String [] pw;
	int mode;
	boolean lose = true;
	boolean rand_setting;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.gamescreen);
    	Bundle bundle = getIntent().getExtras();{
    		try{
    			pw = bundle.getStringArray("passcode");
    			mode = bundle.getInt("mode");
    		}catch(Exception e1){Log.i("Error at bundle ", e1.toString());}}
    	
    	final SharedPreferences settings= getSharedPreferences(PREFS_NAME, 0);
        rand_setting = settings.getBoolean("rand", false);
    	
    	
    	
       activebutton = (Button) findViewById(R.id.r1p1);
       int i, j;
       for (i = 0; i < 10; i++)      
       {
    	   for (j = 0; j < 4; j++)
    	   {
    		  String ButtonID ="r"+(i+1)+"p"+(j+1);    		  
    		  int resID = getResources().getIdentifier(ButtonID, "id", "first.program");
    		  button_guesses[i][j] = ((Button) findViewById(resID));
    		  button_guesses[i][j].setOnClickListener(this);
    		  if ( i > 0 )
    		  {
    			  button_guesses[i][j].setEnabled(false);
    		  }
    	   }
       }
       
 
       Button red = (Button) findViewById(R.id.red);
       red.setOnClickListener(this);
       colors.add(red);
       
       Button green = (Button) findViewById(R.id.green);
       green.setOnClickListener(this);
       colors.add(green);
       
       Button orange = (Button) findViewById(R.id.orange);
       orange.setOnClickListener(this);
       colors.add(orange);
       
       Button black = (Button) findViewById(R.id.black);
       black.setOnClickListener(this);
       colors.add(black);
       
       Button gray = (Button) findViewById(R.id.gray);
       gray.setOnClickListener(this);
       colors.add(gray);
       
       Button blue = (Button) findViewById(R.id.blue);
       blue.setOnClickListener(this);
       colors.add(blue);
       
       Button purple = (Button) findViewById(R.id.purple);
       purple.setOnClickListener(this);
       colors.add(purple);
       
       Button yellow = (Button) findViewById(R.id.yellow);
       yellow.setOnClickListener(this);
       colors.add(yellow);
       
       Button submitGuess = (Button) findViewById(R.id.submitGuess);
       submitGuess.setOnClickListener(this);
       
       
    }    
       
  
       public void onClick(View v){
    	   v.performHapticFeedback(feedbackConstant , 0);
    	   switch(v.getId()){
    	   
    	   case R.id.red:    		   
    		   activebutton.setBackgroundResource(R.drawable.circle_red);
	  		   activebutton.setContentDescription("red"); 
	  		   active_position = (active_position)%4 + 1;
	 		   changeActiveButton(active_position, active_row);     		       		   
    	   break;
    	   
    	   case R.id.black:   		   
    		   activebutton.setBackgroundResource(R.drawable.circle_black);    		  
    		   activebutton.setContentDescription("black");
	 		   active_position = (active_position)%4 + 1;
	 		   changeActiveButton(active_position, active_row);   		    
    	   break;
    	   
    	   case R.id.blue:		   
    		   activebutton.setBackgroundResource(R.drawable.circle_blue); 
    		   activebutton.setContentDescription("blue");
    		   active_position = (active_position)%4 + 1;
	 		   changeActiveButton(active_position, active_row);	 		   
    	   break;
    	   
    	   case R.id.gray:
    		   activebutton.setBackgroundResource(R.drawable.circle_gray);    		  
    		   activebutton.setContentDescription("gray");
	 		   active_position = (active_position)%4 + 1;
	 		   changeActiveButton(active_position, active_row);
    	   break;
    	   
    	   case R.id.green:
    		   activebutton.setBackgroundResource(R.drawable.circle_green);    		  
    		   activebutton.setContentDescription("green");
	 		   active_position = (active_position)%4 + 1;
	 		   changeActiveButton(active_position, active_row);
    	   break;
    	   
    	   case R.id.orange:
    		   activebutton.setBackgroundResource(R.drawable.circle_orange);    		  
    		   activebutton.setContentDescription("orange");
	 		   active_position = (active_position)%4 + 1;
	 		   changeActiveButton(active_position, active_row);
    	   break;
    	   
    	   case R.id.purple:
    		   activebutton.setBackgroundResource(R.drawable.circle_purple);    		  
    		   activebutton.setContentDescription("purple");
	 		   active_position = (active_position)%4 + 1;
	 		   changeActiveButton(active_position, active_row);
    	   break;
    	   
    	   case R.id.yellow:
    		   activebutton.setBackgroundResource(R.drawable.circle_yellow);    		  
    		   activebutton.setContentDescription("yellow");
	 		   active_position = (active_position)%4 + 1;
	 		   changeActiveButton(active_position, active_row);
    	   break;
    	   
    	   case R.id.submitGuess:
    		   // Verify whether or not all the positions have a guess. 
    		   if(checkrow.noWhites(button_guesses, active_row)) 
    		   {
    			   
				   Log.i("GameScreen", "rand_setting is "+rand_setting);
				   Log.i("GameScreen", "noRepeats is "+checkrow.noRepeats(button_guesses, active_row));
    			   if(!rand_setting && !checkrow.noRepeats(button_guesses, active_row)){
    				   
    				Context context = getApplicationContext();
   	 				CharSequence text ="No Repeats Allowed!";
   	 				int duration = Toast.LENGTH_SHORT;
   	 				Toast toast = Toast.makeText (context, text, duration);
   	 				toast.show();
   	 				break;
    			   }
    			   for(int j = 0; j < 4; j++)
	    		   {
	    			   // Disables clicking for the row that was jut guessed.
	    			   button_guesses[active_row][j].setEnabled(false); 
	    			   // Enables the next row of buttons to be clickable. 
	    			   if(active_row != 9)
	    			   {
	    			   button_guesses[active_row+1][j].setEnabled(true);
	    			   }
	    		   }
	    		 
	    		   if(testActiveButton(active_row, button_guesses) == 1)
	    		   {
	    			   Intent myIntent = new Intent(v.getContext(), WinScreen.class);
	    			   myIntent.putExtra("mode", mode);
	    			   startActivity(myIntent);
	    			   lose = false;
	    			
	    		   }
	    		   active_row++; 
	    		   Log.i("cs", "active_row is"+active_row);
	    		  if(lose){
	    			  if((active_row == 10))
	    			  {
	    				  Intent myIntent = new Intent(v.getContext(), LoseScreen.class);
	    				  myIntent.putExtra("passcode", pw);
	    				  myIntent.putExtra("mode", mode);
	    				  startActivity(myIntent);
	    			   
	    			  }
	    			  else
	    			  {
	    				  // Set "activebutton" to the first button in the next row.
	    				  activebutton = button_guesses[active_row][0];
	    				  // reset the active_position to the first in the row.
	    				  active_position = 1; 
	    			  }
	    		  }
    		   }
		   else
    		   {
			   //Prints an error message telling the user to fill any remaining spots with a color.
    			Context context = getApplicationContext();
    			CharSequence text ="Please select a color for any remaining spots.";
    			int duration = Toast.LENGTH_SHORT;
    			
    			Toast toast = Toast.makeText (context, text, duration);
    			toast.show();   
    		   }
    		   
    		   break;
    		   
    	   
    	   default:
    		   // Set the activebutton the the button the user clicks.
    		   activebutton = (Button) findViewById(v.getId()); 
     		   int i;
     		   //Changes the active_position variable to the position # of /
     		   //the button selected.
    		   for(i = 0; i < 4; i++){ 
     			  String temp = activePosition[i];
     			   if(activebutton.getTag().toString().equals(temp)){
     				   active_position = (i%4) + 1; 
     				   changeActiveButton(active_position, active_row);
     			   }
     		   }
    		   break;    	   
    	   }
       }

   	private void changeActiveButton(int actpos, int actrow) {
          // Create string for the ID of the object
	      String aID ="r"+(actrow+1)+"p"+actpos; 
	      // Find the int value for the ID
	      int aresID = getResources().getIdentifier(aID, "id", "first.program");
	      // Set active button designated by the String.
	      activebutton = ((Button) findViewById(aresID));	
		
	}
   
   	
 /*  	
   	// Boolean statement that returns true if there are no "white circles" in the active row
   	// returns false if there is one or more.
	public boolean noWhites(Button[][] b, int row)
	{
		for (int i = 0; i < 4; i++){
			if (b[row][i].getContentDescription().toString().equals("white"))
			{
				return false;
			}
		}
	return true;
	}
	
	*/
	// actrow is the current active_row and barray is the array that contains the button objects.
    private int testActiveButton(int actrow, Button barray[][]) {
    		int return_val = 0;
        	// postman is an ArrayList of boolean values that will indicate
        	//whether or not. It is initialized to contain all false values. 
        	ArrayList<Boolean> postman = new ArrayList<Boolean>();
        	postman.add(false);
        	postman.add(false);
        	postman.add(false);
        	postman.add(false);
        	// verifyPassword stores a local copy of the pw array. It can be changed to "Invalid"
        	//depending on the circumstances.
        	String [] verifyPassword = new String[4];
        	verifyPassword[0] = pw[0];
        	verifyPassword[1] = pw[1];
        	verifyPassword[2] = pw[2];
        	verifyPassword[3] = pw[3];
        	int reds = 0; 
        	int whites = 0;
        	for(int i = 0; i < 4; i++)
        		{
        			// If there is a button in the right spot and is the correct color, add 1 to the 
        			//reds counter and change the string in verifyPassword to Invalid. 
        			if(barray[actrow][i].getContentDescription().toString().equals(verifyPassword[i]))
        			{
        				reds++;
        				postman.set(i, true);
        				verifyPassword[i] = "Invalid";
        				if(reds == 4)
        				{
        					return_val = 1;
        					
        				}
        			}
        		}
        	for(int i = 0; i < 4; i++)
        	{
        		//Checks to see if the postman.get(i) has not been set to true.
        			if(!postman.get(i))
        			{
        				// If there is a button in the right spot and is the correct color, add 1 to the 
            			//whites counter and change the string in verifyPassword to Invalid. 
        				for(int j = 0; j < 4; j++)
        	        	{
        					if(barray[actrow][i].getContentDescription().toString().equals(verifyPassword[j]))
        					{
        					
        					whites++;
        					verifyPassword[j] = "Invalid";
        					break;
        					}
        	        	}
        			}
        	}
          //The following set of instructions will generate the image that shows how many 
         
          // Create string for the ID of the object.
          String aID ="Button"+(actrow+1); 
          // Find the int value for the ID.
  	      int aresID = getResources().getIdentifier(aID, "id", "first.program");
  	      // Set active button to the one designated by the String.
  	      Button answerButton = ((Button) findViewById(aresID));	
  	      aID = "r"+reds+"w"+whites;
  	      aresID = getResources().getIdentifier(aID, "drawable", "first.program");
  	      answerButton.setBackgroundResource(aresID);
  	      return return_val;
        }
    
        
//Disables the back button on the phone.        
@Override
public void onBackPressed(){
return;	
}
}

